package com.csot.ipscan;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.log.Log;

import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

public class IpScanService {

    Log log = Log.getLog(IpScanService.class);

    ExecutorService es = ThreadUtil.newExecutor(5000, 20000, Integer.MAX_VALUE);

    public void handle(Ret ret) throws InterruptedException, ExecutionException {

        if (Objects.isNull(ret) || ret.isEmpty()) {
            return;
        }

        JSONArray ja = ret.getAs("data");

        String[] segment = ja.toArray(new String[]{});

        Deque<String> queue = ListUtil.toLinkedList(segment);

        while (!queue.isEmpty()) {

            if ("stop".equals(SysData.over)) {
                queue.clear();
                SysData.list.clear();
                Thread.currentThread().interrupt();
                break;
            }

            String s = queue.poll();
            List<Callable<String>> clist = new LinkedList<>();
            String[] segs = s.split("-");
            Long start = 0L;
            Long end = 0L;
            if (NumberUtil.isLong(segs[0]))
                start = Long.parseLong(segs[0]);
            else
                start = NetUtil.ipv4ToLong(segs[0]);
            if (NumberUtil.isLong(segs[1]))
                end = Long.parseLong(segs[1]);
            else
                end = NetUtil.ipv4ToLong(segs[1]);

            for (long i = start; i <= end; i++) {
                clist.add(new Task(i));
            }
            List<Future<String>> flist = es.invokeAll(clist);
            int size = flist.size();
            System.out.println(size);
        }

        Ret result = Ret.create();
        result.set("job_id", SysData.job_id);
        result.set("code", "200");
        result.set("data", SysData.list);
        String data = JSON.toJSONString(result);
        try {
            HttpKit.post(PropKit.get("url"), data);
        } catch (Exception e) {
            log.error("", e);
            SysData.postdeque.add(data);
        }


        ThreadUtil.execAsync(() -> {
            log.info(JSON.toJSONString(result));
        });

    }

}
